/**
 * 修复 Element Plus 图片查看器 z-index 问题
 * 使用 MutationObserver 监听 DOM 变化，动态修复 z-index
 */

export function fixImageViewerZIndex() {
  // 创建一个观察器实例
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      mutation.addedNodes.forEach((node) => {
        if (node instanceof HTMLElement) {
          // 检查是否是图片查看器相关的元素
          if (node.classList.contains('el-image-viewer__wrapper')) {
            fixElement(node)
          }
          if (node.classList.contains('el-image-viewer__mask')) {
            fixElement(node, 'mask')
          }
          
          // 检查子元素
          const wrapper = node.querySelector('.el-image-viewer__wrapper')
          const mask = node.querySelector('.el-image-viewer__mask')
          
          if (wrapper) fixElement(wrapper as HTMLElement)
          if (mask) fixElement(mask as HTMLElement, 'mask')
        }
      })
    })
  })

  // 配置观察器
  observer.observe(document.body, {
    childList: true,
    subtree: true
  })

  // 立即检查已存在的元素
  checkExistingElements()

  // 返回清理函数
  return () => observer.disconnect()
}

function fixElement(element: HTMLElement, type: 'wrapper' | 'mask' = 'wrapper') {
  const zIndex = type === 'mask' ? '999998' : '999999'
  
  element.style.setProperty('z-index', zIndex, 'important')
  element.style.setProperty('position', 'fixed', 'important')
  element.style.setProperty('top', '0', 'important')
  element.style.setProperty('left', '0', 'important')
  element.style.setProperty('right', '0', 'important')
  element.style.setProperty('bottom', '0', 'important')
  element.style.setProperty('width', '100vw', 'important')
  element.style.setProperty('height', '100vh', 'important')
  
  if (type === 'mask') {
    element.style.setProperty('background-color', 'rgba(0, 0, 0, 0.5)', 'important')
  }
  
  console.log(`✅ Fixed ${type} z-index to ${zIndex}`)
}

function checkExistingElements() {
  const wrapper = document.querySelector('.el-image-viewer__wrapper')
  const mask = document.querySelector('.el-image-viewer__mask')
  
  if (wrapper) fixElement(wrapper as HTMLElement)
  if (mask) fixElement(mask as HTMLElement, 'mask')
}

